package cn.jyc.ssm03.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

/*
  jackson的工具类:

 */
public class JsonUtil {

    //将ObjectMapper对象定义为工具类的静态成员变量 --- jackson解析器
    private static ObjectMapper mapper = new ObjectMapper();

    //-----------------------------------------------------------

    //将Bean、List<Bean>、Map转成json字符串的封装方法
    public static String objectToJson(Object obj){
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    //-----------------------------------------------------------

    //json字符串转Bean的封装方法
    public static <T> T jsonToBean(String jsonStr, Class<T> clz){
        try {
            return mapper.readValue(jsonStr, clz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    //json字符串数组转List<Bean>的封装方法
    public static <T> List<T> jsonToList(String jsonStr, Class<T> clz){

        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, clz);
        try {
            return mapper.readValue(jsonStr, javaType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    //json字符串转Map的封装方法
    public static Map<String, Object> jsonToMap(String jsonStr){

        JavaType javaType = mapper.getTypeFactory().constructParametricType(Map.class, String.class, Object.class);
        try {
            return mapper.readValue(jsonStr, javaType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
